#pragma once
#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "error.hpp"
namespace xjc
{
    static const int defaultfd = -1;
    static const int gbacklog = 32;
    class Sock
    {
    public:
        Sock() : _sock(defaultfd)
        {
        }
        void Socket()
        {
            _sock = socket(AF_INET, SOCK_STREAM, 0);
            if (_sock < 0)
            {
                std::cerr << "socket error :" << errno << strerror(errno) << std::endl;
                exit(SOCKET_ERR);
            }
        }
        void Bind(const uint16_t &port)
        {
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_addr.s_addr = INADDR_ANY;
            local.sin_port = htons(port);
            if (bind(_sock, (struct sockaddr *)&local, sizeof(local) )<0)
            {
                std::cerr << "bind error :" << errno << strerror(errno) << std::endl;
                exit(BIND_ERR);
            }
        }
        void Listen()
        {
            if (listen(_sock, gbacklog) < 0)
            {
                std::cerr << "listen error :" << errno << strerror(errno) << std::endl;
                exit(LISTEN_ERR);
            }
        }
        int Accept(std::string *clientip, uint16_t *clientport)
        {
            struct sockaddr_in clientinfo;
            socklen_t len = sizeof(clientinfo);
            int clientsock = accept(_sock, (struct sockaddr *)&clientinfo, &len);
            if (clientsock < 0)
            {
                std::cerr << "accept error :" << errno << strerror(errno) << std::endl;
            }
            else
            {
                *clientip = inet_ntoa(clientinfo.sin_addr);
                *clientport = ntohs(clientinfo.sin_port);
            }
            return clientsock;
        }
        int Connect(const std::string &serverip, const uint16_t &serverport)
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_addr.s_addr = inet_addr(serverip.c_str());
            server.sin_port = htons(serverport);
            return connect(_sock, (struct sockaddr *)&server, sizeof(server));
        }
        int GetFd()
        {
            return _sock;
        }
        ~Sock()
        {
            if (_sock != defaultfd)
            {
                close(_sock);
            }
        }

    private:
        int _sock;
    };
}